﻿using Kinlo.Entitys;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using UIWindows.GlobalStatics;
using UIWindows.Services.Context;
using UIWindows.Tools.Helper;
using XingLucifer.Devices;
using XingLucifer.IBase.Enums;

namespace UIWindows.Services.Handle
{
    [Attributes.TaskClass(TaskTypes.注液量发送)]
    public class LiquidInjectionPump : ServierBase
    {
        Dictionary<string,int> _keyValues;
        public LiquidInjectionPump(DeviceConfigStatic deviceConfig, SystemConfigStatic systemConfig,
            UserConfigStatic userConfig, ParameterStatic parameterStatic, TemporaryStatic temporaryStatic, HomeStatic homeStatic, MesParameterStatic mesParameterStatic)
            : base(deviceConfig, systemConfig, userConfig, parameterStatic, temporaryStatic, homeStatic, mesParameterStatic)
        {
            //PC_InjectionVolume
            _keyValues = new Dictionary<string, int>() {
                { "PC_InjectionVolume[0]", 3500 },
                { "PC_InjectionVolume[2]", 3500 },
                { "PC_InjectionVolume[4]", 3500 },
                { "3", 3500 },
                { "4", 3500 },
                { "5", 3500 },
                //=============//
                { "PC_InjectionVolume[1]", 3520 },
                { "PC_InjectionVolume[3]", 3520 },
                { "PC_InjectionVolume[5]", 3520 },
                { "9", 3520 },
                { "10", 3520 },
                { "11", 3520 },
            };
        }

        public override Task Handle(DataContext context)
        {
            if (!ClearSignal(context)) { return Task.CompletedTask; }
            try
            {
                var plc = _deviceConfig.DeviceList.FirstOrDefault(x => x.ServiceName == context.ServiceName && x.TaskType == TaskTypes.扫描信号).Communication as OmronCIP;
                DateTime weighing_time = DateTime.Now;
               RunLog( $"读取标签：{context.Address_Struct}数据", MessageLevelType.信息);
                var erinnerungen = ReadOneErinnerungen(plc, context.Address_Struct, context.Struct_Length, _systemConfig.IAddress.Erinnerungen_InjectionVolume, context.AddressingMethod);
                if (erinnerungen.Item1)
                {
                    $"==>>{context.TaskType}<<==\r\n收到启动信号，没收到电池记忆，请联系电气工程师！！！".MessageDialogs(MessageLevelType.错误, false, Enums.PopUpTypes.Global);
                    return base.Handle(context);
                }
                RunLog($"记忆ID：{erinnerungen.Item2.SnowflakeId}");
                Models.Devices.DeviceClientModel? device = _deviceConfig.DeviceList.FirstOrDefault(x => x.ServiceName == context.ServiceName && x.TaskType == context.TaskType
                && x.DeviceType == context.DeviceType && x.Index == context.DeviceIndex);
                var battery = erinnerungen.Item2;
                if (battery.SnowflakeId == -1)
                {
                    RunLog($"-[{battery.Index}] 点检注液量：{battery.Data_PLC} g");
                    bool bl1 = false;
                    if (device == null)
                    {
                        RunLog($"找不到[{context.DeviceIndex}]号设备", MessageLevelType.错误);
                        bl1 = true;
                    }
                    else
                    {
                        bl1 = SendInj(battery.Data_PLC, _keyValues[context.Address_Struct], device);
                    }
                    WriteResult("",bl1 ? ResultTypes.合格 : ResultTypes.不合格, plc, battery.Address_Struct, context);
                    return base.Handle(context);
                }
                DateTime dateTime = DateTime.Now;
                ProductionData? entity = _temporaryStatic.EntityCache.FirstOrDefault(x => x.SnowflakeId == battery.SnowflakeId);
                if (entity == null)
                {
                    RunLog($"-[{battery.Index}] 实体缓存查询不到==>[{battery.SnowflakeId}]，转到数据库查询");
                    entity = dateTime.GetEntity(context.TaskType, battery.SnowflakeId, DBSuffix);
                }
                else
                {
                    ProductionData.Meta.TableName = entity.Items["TableName"].ToString();
                }
                if (entity == null)
                {
                    RunLog($"-[{battery.Index}] 数据库找不到ID为：{battery.SnowflakeId}");
                    WriteResult("",ResultTypes.数据库找不到电池, plc, battery.Address_Struct, context);
                    return base.Handle(context);
                }
                bool? bl = null;
                if (battery.Data_PLC > ((float)entity.TargetInjectionVolume) - 0.1 && battery.Data_PLC < ((float)entity.TargetInjectionVolume) + 0.1)
                {
                    if (device == null)
                    {
                        bl = true;
                        RunLog($"-[{context.Address_Struct}] 找不到[{battery.Index}]#注液泵设备");
                    }
                    else
                    {
                        bl = SendInj(battery.Data_PLC, _keyValues[context.Address_Struct], device);
                    }
                    RunLog($"-[{battery.Index}] ID：[{battery.SnowflakeId}] 条码：[{entity.BarCode}] 注液量：[{battery.Data_PLC}] 发送结果：{(bl == true ? "成功" : "失败")}");
                }
                else
                {
                    RunLog($"-[{battery.Index}] ID：[{battery.SnowflakeId}] 条码：[{entity.BarCode}] 注液量对比失败 记忆注液量：[{battery.Data_PLC}] 电池注液量：[{entity.TargetInjectionVolume}]");
                }
                if(bl==null)
                {
                    entity.ResultInjSend = ResultTypes.注液量不匹配;
                }else if(bl==true)
                {
                    entity.ResultInjSend = ResultTypes.合格;
                }
                else
                {
                    entity.ResultInjSend = ResultTypes.注液量发送失败;
                }
                entity.ResultInjSend = bl == null ? ResultTypes.注液量不匹配 : (bl == true ? ResultTypes.合格 : ResultTypes.注液量发送失败);    
                

                if(entity.ResultInjSend==ResultTypes.合格 && (entity.ResultTotal==ResultTypes.合格|| entity.ResultTotal == ResultTypes._))
                {
                    WriteResult(entity.BarCode, entity.ResultInjSend, plc, battery.Address_Struct, context);
                }else
                {
                    WriteResult(entity.BarCode, entity.ResultTotal, plc, battery.Address_Struct, context);
                }

                try
                {
                   
                    entity.Update();
                }
                catch (Exception ex)
                {
                    RunLog($"-[{battery.Index}] ID：[{battery.SnowflakeId}] 条码：[{entity.BarCode}] 数据更新异常：{ex}");
                }

                //WriteResult(entity.BarCode, entity.ResultInjSend, plc, battery.Address_Struct, context);
            }
            catch (Exception ex)
            {
                RunLog($"-[{context.Address_Struct}] 异常：{ex}");
            }
            return base.Handle(context);
        }

       
    }
}
